package org.vison.wonfu.framework.configure;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

public class HttpUtils {

    public static String getRealClientIp(HttpServletRequest request, boolean trustProxy) {
        String forwardIpsStr = request.getHeader("x-forwarded-for");
        if (trustProxy && StringUtils.isNotBlank(forwardIpsStr)) {
            List<String> forwardIps = Arrays.asList(forwardIpsStr.split(","));
            if (forwardIps.size() > 0) {
                return forwardIps.get(0);
            }
        }
        return request.getRemoteAddr();

    }

    public static Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> headerMap = new HashMap<>();
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            String value = request.getHeader(name);
            headerMap.put(name, value);
        }
        return headerMap;
    }

}
